#!/usr/bin/expect
set timeout 1
#获取参数
set port [lindex $argv 0]
set sshIp [lindex $argv 1]
set sshUser [lindex $argv 2]
set sshPass [lindex $argv 3]
set sshRootPass [lindex $argv 4]
set sshNewUser [lindex $argv 5]
set sshNewGroup [lindex $argv 6]
set rootPath [lindex $argv 7]

#开启子进程
spawn ssh ${sshUser}@${sshIp} -p ${port}
#第一次需要输入时，有两种情况
expect "*yes/no*" {send "yes\r"}\
		"*password:*" {send "${sshPass}\r"}
#第二次需要输入
expect "*password:*" {send "${sshPass}\r"}\
		"*$*" {send "\r"}
expect "*$*"
send "cd \r"
expect "*$*"
send "chmod +x beetle_terminal_user_create.sh\r"
expect {
    "*No such file*" { exit 1 }
}
expect "*$*"
send "su\r"
expect "*assword*" {send "${sshRootPass}\r"}\
		"*$*" {send "\r"}
expect "*$*"
send "userdel -r ${sshNewUser} \r"
expect {
    "*is currently used*" { exit 1 }
}
expect "*$*"
send "rm -rf ${rootPath} \r"
expect "*$*"
send "./beetle_terminal_user_create.sh ${sshNewGroup} ${sshNewUser}\r"
expect {
    "*No such file*" { exit 1 }
}
expect "*$*"
send "rm -rf beetle_terminal_user_create.sh\r"
expect "*$*"
send "cd /home/${sshNewUser}/\r"
expect {
    "*No such file*" { exit 1 }
}
expect "*$*"
send "mkdir .ssh\r"
expect "*$*"
send "chmod 700 .ssh\r"
expect {
    "*No such file*" { exit 1 }
}
expect "*$*"
send "cd .ssh\r"
expect "*$*"
send "mv /home/${sshUser}/id_rsa.pub id_rsa.pub\r"
expect {
    "*No such file*" { exit 1 }
}
expect "*$*"
send "touch authorized_keys\r"
expect "*$*"
send "chmod 600 authorized_keys\r"
expect "*$*"
send "cat id_rsa.pub >> authorized_keys\r"
expect {
    "*No such file*" { exit 1 }
}
#expect "*$*"
#send "rm -rf id_rsa.pub\r"
expect "*$*"
send "cd /home/${sshNewUser}/\r"
expect "*$*"
send "mkdir .Beetle\r"
expect "*$*"
send "mv /home/${sshUser}/id_rsa /home/${sshNewUser}/.Beetle/common_id_rsa\r"
expect {
    "*No such file*" { exit 1 }
}
expect "*$*"
send "mv /home/${sshNewUser}/.ssh/id_rsa.pub /home/${sshNewUser}/.Beetle/id_rsa.pub\r"
expect {
    "*No such file*" { exit 1 }
}
expect "*$*"
send "chmod 600 /home/${sshNewUser}/.Beetle/*\r"
expect "*$*"
send "chown -R ${sshNewUser}:${sshNewGroup} /home/${sshNewUser}/.ssh\r"
expect "*$*"
send "chown -R ${sshNewUser}:${sshNewGroup} /home/${sshNewUser}/.Beetle\r"
expect "*$*"
send "mkdir shell\r"
expect "*$*"
send "chown -R ${sshNewUser}:${sshNewGroup} /home/${sshNewUser}/shell\r"
expect "*$*"
send "mkdir -p ${rootPath}\r"
expect "*$*"
send "chown -R ${sshNewUser}:${sshNewGroup} ${rootPath}\r"
#expect "*$*"
#send "exit"
expect eof
exit